//
//  YDWebViewController.m
//  YunDongGym
//
//  Created by lqq on 2018/6/8.
//  Copyright © 2018年 lqq. All rights reserved.
//

#import "YDWebViewController.h"
#import "YDWebView.h"
#import "UIButton+Extension.h"
#import "ShareTool.h"
@interface YDWebViewController ()<WKNavigationDelegate,YDWebViewDelegate>
@property(nonatomic ,strong) NSString *webUrl;
@property (nonatomic, strong) NSString *titleStr;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) YDWebView *webView;
@property (nonatomic, strong) UIButton *closeBtn;
@end

@implementation YDWebViewController
#pragma mark Class Method
+ (instancetype)controllerWithUrl:(NSString *)url
{
    YDWebViewController *webVC = [[YDWebViewController alloc] init];
    webVC.webUrl = url;
    return webVC;
}

+ (instancetype)controllerWithUrl:(NSString *)url title:(NSString *)title
{
    YDWebViewController *webVC = [YDWebViewController controllerWithUrl:url];
    webVC.titleStr = title;
    return webVC;
}

#pragma mark Life Circle
- (void)viewDidLoad {
    [super viewDidLoad];
    if (![self.webUrl containsString:@"#"]) {
        self.webUrl = [self.webUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    [self configUI];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self startLoad];
}

- (void)dealloc
{
    NSLog(@"%s",__func__);
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];

}

#pragma mark Config/UI
- (void)configUI
{
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, [Toolkit getSystemNavHeight])];
    navView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:navView];
    [navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.equalTo(@([Toolkit getSystemNavHeight]));
    }];
    UIView *navContentView = [[UIView alloc] initWithFrame:CGRectMake(0, [Toolkit getStatusBarHeight], navView.width, 44)];
    [navView addSubview:navContentView];
    [navContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(navView);
        make.height.equalTo(@(44));
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [backBtn setImage:[UIImage originImageWithImageName:@"ic_58_back1_normal"] forState:UIControlStateNormal];
    [navContentView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(goBackBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(navContentView).offset(5);
        make.centerY.equalTo(navContentView);
        make.width.height.equalTo(@(44));
    }];
    
    _closeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_closeBtn setTintColor:HEXColor(@"0E1C29")];
    [_closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [_closeBtn addTarget:self action:@selector(closeBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    _closeBtn.hidden = YES;
    [navContentView addSubview:_closeBtn];
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backBtn.mas_right);
        make.width.height.centerY.equalTo(backBtn);
    }];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLabel.font = MediumFont(17);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 2;
    titleLabel.textColor = [UIColor colorWithHexString:@"#0E1C29"];
    titleLabel.text = _titleStr;
    [navContentView addSubview:titleLabel];
    _titleLabel = titleLabel;
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(navContentView).offset(88);
        make.right.equalTo(navContentView).offset(-88);
        make.centerY.equalTo(navContentView);
    }];
    
    _progressView = [[UIProgressView alloc] init];
    [navContentView addSubview:_progressView];
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(navContentView);
        make.height.equalTo(@(1));
    }];
    self.progressView.backgroundColor = HEXColor(@"#3AA7FF");
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    
    _webView = [[YDWebView alloc] init];
    _webView.YDWebDelegate = self;
    [self.view addSubview:_webView];
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(navView.mas_bottom);
    }];
    _webView.allowsBackForwardNavigationGestures = YES;
    [_webView.bridge setWebViewDelegate:self];
    
    switch (_urlType) {
        case YDWebUrlType_Normal:
        {
            
        }
            break;
        case YDWebUrlType_Home:
        {
            backBtn.hidden = YES;
        }
            
        default:
            break;
    }
}
#pragma mark Action
- (void)goBackBtnClicked
{
    if ([_webView canGoBack]) {
        [_webView goBack];
        _closeBtn.hidden = NO;
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)closeBtnClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark Pravate
- (void)startLoad
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_webUrl]];
    request.timeoutInterval = 15.0f;
    [self.webView loadRequest:request];
}


#pragma mark - WKWKNavigationDelegate Methods

/*
 *5.在WKWebViewd的代理中展示进度条，加载完成后隐藏进度条
 */

//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
    self.webUrl = [NSString stringWithFormat:@"%@",webView.URL];
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    //加载完成后隐藏progressView
    //    self.progressView.hidden = YES;
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}

#pragma mark KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.4倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
                
            }];
        }
    } else if ([keyPath isEqualToString:@"title"]) {
//        _titleStr = _webView.title;
//        self.titleLabel.text = _titleStr;
    } else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


#pragma mark YDWebViewDelegate
- (void)setControllerTitle:(NSString *)title
{
    self.titleLabel.text = title;
}



@end
